<template>
  <div class="mine-edit">
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />
    <!-- 头像 -->
    <div class="avatar">
      <van-image
        width="100"
        height="100"
        fit="cover"
        round
        :src="userInfo.photo"
      />
      <!-- 头像 -->
      <van-uploader :after-read="afterRead" />
    </div>

    <!-- 3. 资料cell区域   is-lin是个箭头 -->
    <van-cell
      title="名称"
      :value="userInfo.name"
      is-link
      @click="showNameDialog"
    />

    <van-cell
      title="性别"
      :value="userInfo.gender ? '男' : '女'"
      is-link
      @click="popShow = true"
    />
    <van-cell
      title="生日"
      :value="userInfo.birthday"
      is-link
      @click="birthdayShow"
    />
    <!-- 组件     confirm事件点击确认按钮触发-->
    <van-dialog
      v-model="show"
      title="修改名称"
      show-cancel-button
      @confirm="changeName"
    >
      <van-cell-group> <van-field v-model="value" ref="inp" /></van-cell-group>
    </van-dialog>

    <!-- 展示男女 -->
    <van-popup v-model="popShow" position="bottom" :style="{ height: '20%' }">
      <van-nav-bar title="修改性别" left-text="取消" />
      <van-cell @click="changeSex(1)" title="男" is-link />
      <van-cell @click="changeSex(0)" title="女" is-link />
    </van-popup>
    <!-- close-on-click-action   点击选项关闭  '-->

    <!-- 日期 -->
    <van-popup v-model="popupShow" position="bottom" :style="{ height: '45%' }">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="pic"
        @cancel="popupShow = false"
      />
    </van-popup>

    <!-- 裁剪容器 -->
    <div class="crop-wrap" v-show="cropShow">
      <vueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        autoCropWidth="150"
        autoCropHeight="150"
      ></vueCropper>
      <van-button @click="doCrop" type="primary">裁剪</van-button>
      <van-button @click="cropShow = false" type="primary">取消</van-button>
    </div>
  </div>
</template>
<script>
import { editProfileAPI, headPortraitAPI } from "@/api";
import { VueCropper } from "vue-cropper";
// 导入时间插件
import moment from "moment";

export default {
  components: {
    VueCropper,
  },
  data() {
    return {
      minDate: new Date(2000, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      popupShow: false,
      show: false,
      value: "",
      popShow: false,
      cropShow: false,
      cropImg: "",
    };
  },

  methods: {
    showNameDialog() {
      this.show = true;
      this.value = this.userInfo.name;
      this.$nextTick(() => {
        this.$refs.inp.focus();
      });
    },

    // 3. 修改性别
    async changeSex(gender) {
      // 优化一下性能：判断如果要修改的性别跟之前的性别一样，就没必要往下执行
      if (gender === this.userInfo.gender) {
        this.popShow = false;
        return;
      }

      // 发请求去修改
      await editProfileAPI({
        gender,
      });

      // 修改成功要改掉vuex里的数据，界面才会变
      this.$store.commit("setUserInfo", {
        // 要保留原来的数据，只单独修改name
        ...this.$store.state.userInfo,
        gender,
      });

      // 隐藏弹出层
      this.popShow = false;
    },
    birthdayShow() {
      // 将当前时间赋值给时间选择器 ,
      this.currentDate = new Date(this.userInfo.birthday);
      // console.log(this.userInfo.birthday);
      // console.log(new Date(this.userInfo.birthday));

      this.popupShow = true;
    },

    // 日期确定按钮
    async pic() {
      // 将当前时间转换为string类型
      const birthday = moment(this.currentDate).format("YYYY-MM-DD");
      // console.log(birthday);
      await editProfileAPI({
        birthday,
      });
      //  / 修改成功，还要改掉vuex里的值
      this.$store.commit("setUserInfo", {
        // 要保留原来的数据，只单独修改birthday
        ...this.$store.state.userInfo,
        birthday,
      });
      this.popupShow = false;
    },

    // 文件上传选择完文件后触发的函数
    afterRead(file) {
      //   // file里包含了当前选择的文件信息
      //     // content属性有选择的图片对应的base64编码

      // console.log('选择完文件了', file.content);
      //     // file属性就有这张文件对象
      // console.log("选择完文件了", file.file);
      // 显示裁剪容器
      this.cropShow = true;
      //  console.log(this.cropShow);
      this.cropImg = file.content; //需求要的是base64编码
    },
    doCrop() {
      // console.log(photo);
      this.$refs.cropper.getCropBlob(async (data) => {
        let fm = new FormData();
        fm.append("photo", data);

        // 获取fm中的数据
        let res = await headPortraitAPI(fm);
        // console.log(res);
        this.cropper = res.data.data.photo;
        this.cropShow = false;

        // 将修改好的头像存入vuex
        await editProfileAPI({
          photo: this.cropper,
        });
        // //  / 修改成功，还要改掉vuex里的值
        this.$store.commit("setUserInfo", {
          //   // 要保留原来的数据，只单独修改name
          ...this.$store.state.userInfo,
          photo: this.cropper,
          //   // gender:this.val,
        });
        this.$toast.success('修改成功！')
      });
    },
    async changeName() {
      // 获取用户信息
      await editProfileAPI({
        name: this.value,
      });
      // //  / 修改成功，还要改掉vuex里的值
      this.$store.commit("setUserInfo", {
        //   // 要保留原来的数据，只单独修改name
        ...this.$store.state.userInfo,
        name: this.value,
        //   // gender:this.val,
      });
    },
  },

  created() {
    this.$store.dispatch("reqUserInfo");
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo;
    },
  },
};
</script>

<style lang="less" scoped>
.mine-edit {
  .avatar {
    height: 140px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;

    .van-image {
      width: 120px;
      height: 120px;
    }

    .van-uploader {
      width: 100vw;
      height: 100vh;
      position: absolute;
      opacity: 0;
      background-color: brown;

      ::v-deep {
        .van-uploader__wrapper {
          width: 100%;
          height: 100%;

          .van-uploader__upload {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }

  .dialog-name {
    .van-field {
      border: 1px solid #ddd;
    }
  }
  .crop-wrap {
    // 铺满整个屏幕
    // vw: viewport width 视口宽度
    // vh：viewport height 视口高度
    // 把视口宽度和高度各自分成100份，写100代表铺满
    width: 100vw;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    background-color: #f00;
    .van-button {
      position: fixed;
      bottom: 0;
      left: 0;
      &:nth-of-type(2) {
        left: auto;
        right: 0;
      }
    }
  }
}
</style>